package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.bean.User;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.common.SMSUtils;
import com.itheima.common.ValidateCodeUtils;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //1.生成验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        //2.发送验证码
        //SMSUtils.sendMessage("瑞吉外卖","瑞吉外卖",user.getPhone(),code);
        log.info("code：{}",code);

        //3.使用session存储验证码 方便后续和用户输入的验证码进行比对
        session.setAttribute(user.getPhone(),code);

        //4.返回验证码发送成功
        return R.success(code);
    }

    /**
     * 用户登录
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String,Object> map,HttpSession session){
        //1.获取用户输入的手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //2.从session中获取服务器生成的验证码  存到session时以手机号为key
        String sessionCode = session.getAttribute(phone).toString();

        //3.比对验证码
        if(sessionCode!=null && sessionCode.equals(code)){
            //4.1：比对一致 登录成功 完成自动注册【查询数据库看是否存在该手机号对应的用户】
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User one = userService.getOne(wrapper);
            if(one==null){
                //说明第一次登录 完成自动注册
                one = new User();
                one.setPhone(phone);
                one.setName("m_"+phone);
                userService.save(one);
            }

            //将用户id保存到session中
            session.setAttribute("user",one.getId());
            BaseContext.setCurrentId(one.getId());
            return R.success("登录成功！");
        }else{
            //4.2：比对不一致 登录失败
            return R.error("登录失败！");
        }


    }


    @PostMapping("/logout")
    public R<String > logout(HttpSession session){

        session.invalidate();

        return R.success("退出成功");
    }
}
